package cfdt.ldl.signatrue.util;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import cfdt.tools.util.StringUtils;

public class SortUtils {

    private SortUtils() {
    }

    /**
     * 参数根据key的 ASCII 码从小到大排序（字典序）
     *
     * @param params
     * @param keyName
     * @param isAppendKey
     * @return
     */
    public static StringBuilder sort(Map<String, Object> params, String keyName, boolean isAppendKey,
                                     boolean isAppendNullValue, boolean isDeleteLastLink, String keyValueLink, String keyPairLink) {
        Map<String, Object> paramMap = new TreeMap<String, Object>(params); // TreeMap可以自动排序
        StringBuilder result = new StringBuilder();

        for (Entry<String, Object> entry : paramMap.entrySet()) {
            String value = entry.getValue() == null ? "" : String.valueOf(entry.getValue());
            if (!keyName.equals(entry.getKey())
                    && (isAppendNullValue || StringUtils.isNotEmpty(value))) {
                if (isAppendKey) {
                    result.append(entry.getKey());
                    result.append(StringUtils.trim(keyValueLink));
                }
                result.append(value).append(StringUtils.trim(keyPairLink));
            }
        }
        if (isDeleteLastLink) {
            result.deleteCharAt(result.length() - StringUtils.trim(keyPairLink).length());
        }

        return result;
    }
}
